import asyncio
import os
import signal

TIMEOUT = 60


async def wait_for_logfile(fname: str):
    for i in range(TIMEOUT):
        with open(fname) as ifile:
            for line in ifile.readlines():
                if 'Starting to catch signals' in line:
                    # Yes, sleeping for sync. Yes, that's bad.
                    # No, it is not possible to wait for a specific event.
                    await asyncio.sleep(1)
                    return

        # not yet started, waiting
        await asyncio.sleep(1)

    assert False, f'log file {fname} does not contain start log entry, has the service started?'


async def test_boot_logs(
    service_binary,
    service_config_path_temp,
    service_env,
    create_daemon_scope,
    ensure_daemon_started,
    _service_logfile_path,
):
    async def _checker(*, session, process) -> bool:
        return True

    async with create_daemon_scope(
        args=[
            str(service_binary),
            '--config',
            str(service_config_path_temp),
        ],
        health_check=_checker,
        env=service_env,
    ) as scope:
        daemon = await ensure_daemon_started(scope)

        await wait_for_logfile(_service_logfile_path)

        os.remove(_service_logfile_path)
        assert not os.path.exists(_service_logfile_path)

        daemon.process.send_signal(signal.SIGUSR1)

        for i in range(TIMEOUT):
            if os.path.exists(_service_logfile_path):
                break
            await asyncio.sleep(1)
        else:
            assert False, f'log file {_service_logfile_path} is not reopened'
